package Servlet;

import Entity.Friends;
import Entity.Player;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author ori
 */
public class PlayersSearchServlet extends HttpServlet {

    List<String> friendsList = new ArrayList<String>();
    String userName = "clara";

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if(request.getParameter("userName")==null){
            request.setAttribute("friendslist",searchPlayers(request.getParameter("searchedName")));
        }
        else{
            friendsList = getFriends(request.getParameter("userName"));
            request.setAttribute("friendslist", getPlayers(request.getParameter("userName")));
        }
        // Now that the controller has gathered the data from the model,
        // pass the data onto the view to render it as JSON.
        RequestDispatcher view = request.getRequestDispatcher("/friends_view.jsp");
        view.forward(request, response);
    }

    private List<String> getFriends(String userName) {
        List<String> friendsInfo = new ArrayList<String>();

        try {

            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            Query p = em.createNamedQuery("Friends.findByUserName").setParameter("userName", userName);
            List<Friends> results = p.getResultList();
            for (Friends c : results) {
                friendsInfo.add(c.getFriendsPK().getFriend());
            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        return friendsInfo;
    }


    //Search to find out if a player is also a friend. If it's a friend then we don't includ eon list.
    private List<Map<String, String>> getPlayers(String playerName) {
        List<Map<String, String>> playersInfo = new ArrayList<Map<String, String>>();

        try {

            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            Query p = em.createNamedQuery("Player.findAllNotPlayer").setParameter("playerName", playerName);
            List<Player> results = p.getResultList();
            for (Player c : results) {
                int isFriend = 0;

                for (int i = 0; i < friendsList.size(); i++) {
                    if (friendsList.get(i).equals("" + c.getPlayName())) {
                        isFriend = 1;
                        break;
                    }
                }

                if (isFriend == 0) {
                    Map<String, String> players = new HashMap<String, String>();
                    players.put("friendName", c.getPlayName());
                    players.put("friendLevel", "" + c.getFurthestPlayedLevel());
                    players.put("friendScore", "" + c.getAccumScore());
                    players.put("friendPicture", "" + c.getPicture());
                    players.put("friendOnline", "" + c.getIsOnline());
                    playersInfo.add(players);
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


        return playersInfo;
    }

        private List<Map<String, String>> searchPlayers(String searchedName) {
        List<Map<String, String>> playersInfo = new ArrayList<Map<String, String>>();

        try {

            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            Query p = em.createNamedQuery("Player.findByPlayName").setParameter("playName", searchedName);
            List<Player> results = p.getResultList();
            for (Player c : results) {
                    Map<String, String> players = new HashMap<String, String>();
                    players.put("friendName", c.getPlayName());
                    players.put("friendLevel", "" + c.getFurthestPlayedLevel());
                    players.put("friendScore", "" + c.getAccumScore());
                    players.put("friendPicture", "" + c.getPicture());
                    playersInfo.add(players);

            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


        return playersInfo;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
